package fanshe3;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestPerson {
    // public static final String 小明 = "小明";
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Teacher teacher = new Teacher();
        String typeInstance = getTypeInstance(teacher);
        System.out.println("typeInstance = " + typeInstance);
// Student student = new Student();
// String typeInstance1 = getTypeInstance(student);
// System.out.println("typeInstance1 = " + typeInstance1);
//测试反射
        Student student = new Student();
        String typeInvoke = getTypeInvoke(student);
        System.out.println("typeInvoke = " + typeInvoke);
    }
    /**
     * 无反射操作
     *
     * @return
     */
    public static String getTypeInstance(Object obj) {
        if (obj instanceof Student) {
            Student student = (Student) obj;
            String userType = student.getUserType("小明");
            return userType;
        }
        if (obj instanceof Teacher) {
            Teacher teacher = (Teacher) obj;
            String userType = teacher.getUserType("张老师");
            return userType;
        }
        return null;
    }
    /**
     * 使用反射操作类
     *
     */
    public static String getTypeInvoke(Object obj) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<?> aClass = obj.getClass();
        Object instance = aClass.newInstance();
        Method getUserType = aClass.getMethod("getUserType", String.class);
        String invoke = (String) getUserType.invoke(instance, "小明");
        return invoke;
    }
}
